<template>
  <view>
    <view class="example">
      <uni-forms ref="form" :modelValue="establishFrom" :rules="rules">
        <uni-forms-item :label="Warehouse" name="warehouse_id" required>
          <uni-data-select
            v-model="establishFrom.warehouse_id"
            :localdata="warehouseNewList"
            @change="changeWarehous"
            :clear="false"
			 :placeholder="PleaseSelect"
          ></uni-data-select>
        </uni-forms-item>
        <uni-forms-item :label="Client" name="user_id" required>
          <uni-data-select
            v-model="establishFrom.user_id"
            :localdata="memberNewList"
            :clear="false"
            @change="changeClient"
			 :placeholder="PleaseSelect"
          ></uni-data-select>
        </uni-forms-item>
        <uni-forms-item :label="ClientAddress" name="address_id" required>
          <uni-data-select
            :placeholder="Customer"
            v-model="establishFrom.address_id"
            :localdata="deliveryList"
            :clear="false"
          ></uni-data-select>
        </uni-forms-item>
        <uni-forms-item :label="Commodity" name="product_info" required>
          <zxz-uni-data-select
            :placeholder="Selecthouse"
            :multiple="true"
            :filterable="true"
            v-model="establishFrom.product_info"
            :localdata="commoditylist"
            @change="inputChange"
          >
          </zxz-uni-data-select>
        </uni-forms-item>

        <view
          class="commodity_box"
          :style="{
            height: establishFrom.newProduct.length >= 4 ? '220rpx' : '',
          }"
        >
          <view
            v-for="(item, index) in establishFrom.newProduct"
            :key="index"
            class="commodity"
          >
            {{ item.text }}
            <fui-button v-model="item.num" />
          </view>
        </view>

        <uni-forms-item :label="PaymentType" name="pay_type" required>
          <uni-data-checkbox
            v-model="establishFrom.pay_type"
            :localdata="payTypeList"
            @change="changeType"
          />
        </uni-forms-item>
        <uni-forms-item
          :label="PaymentTime"
          name="repayment_time"
          :required="requiredTime"
          v-if="requiredTime"
        >
          <uni-datetime-picker
            type="date"
            return-type="timestamp"
            v-model="establishFrom.repayment_time"
            :placeholder="SelectTime"
          />
        </uni-forms-item>
        <uni-forms-item :label="Remark" name="message">
          <uni-easyinput
            maxlength="50"
            type="textarea"
            v-model="establishFrom.message"
            :placeholder="EnterMark"
          />
        </uni-forms-item>
      </uni-forms>
    </view>
    <button type="primary" class="operation" @click="submit">
      {{ $t("common.Submit") }}
    </button>
  </view>
</template>

<script>
import fuiButton from "@/components/fui-input-number/fui-input-number.vue";
import {
  warehouseList,
  memberList,
  specification,
  addresslist,
  addcreate,
} from "@/api/warehouse.js";
export default {
  data() {
    return {
      establishFrom: {
        warehouse_id: "", //仓库
        user_id: "", //客户ID
        address_id: "", //客户地址
        product_info: [], //商品
        message: "", //备注
        pay_type: 0, //支付类型 0 先款后货 1先货后款
        repayment_time: "", //还款时间

        newProduct: [], //商品参数（需要删除）
      },
      requiredTime: false,
      rules: {
        warehouse_id: {
          rules: [
            {
              required: true,
              errorMessage: "请选择仓库",
            },
          ],
        },
        user_id: {
          rules: [
            {
              required: true,
              errorMessage: "请选择客户",
            },
          ],
        },
        address_id: {
          rules: [
            {
              required: true,
              errorMessage: "请选择客户地址",
            },
          ],
        },
        product_info: {
          rules: [
            {
              required: true,
              errorMessage: "请选择商品",
            },
          ],
        },
        repayment_time: {
          rules: [
            {
              required: true,
              errorMessage: "请选择付款时间",
            },
          ],
        },
      },
      payTypeList: [
        {
          text: this.$t('orderFrom.PayUpfront'),
          value: 0,
        },
        {
          text: this.$t('orderFrom.ShipFirst'),
          value: 1,
        },
      ],
      warehouseNewList: [], //仓库列表
      commoditylist: [], //商品列表
      memberNewList: [], //客户列表
      deliveryList: [], //客户地址
    };
  },
  components: {
    fuiButton,
  },

  onShow() {
    this.gatherList();
    uni.setNavigationBarTitle({
      title: "创建订单",
    });
  },
  methods: {
    gatherList() {
      // 仓库列表
      warehouseList(0).then((res) => {
        if (res.length) {
          res = res.map((code) => {
            return {
              ...code,
              text: code.name,
              value: code.id,
            };
          });
        }
        this.warehouseNewList = res;
      });
      // 客户列表
      memberList().then((res) => {
        if (res.data.length) {
          res.data = res.data.map((code) => {
            return {
              ...code,
              text: code.name,
              value: code.id,
            };
          });
        }
        this.memberNewList = res.data;
      });
    },

    changeWarehous(e) {
      this.establishFrom.newProduct = [];
      // 选择仓库时,调用商品接口列表
      this.getSpecification(e);
    },
    getSpecification(e) {
      // 仓库商品规格（商品列表）
      specification(e).then((res) => {
        if (res.data.length) {
          res.data = res.data.map((code) => {
            return {
              ...code,
              text: code.name,
              value: code.id,
              num: 1,
            };
          });
        }
        this.commoditylist = res.data;
      });
    },
    changeClient(e) {
      // 选择客户时,调用客户收货地址列表
      this.getAddresslist(e);
    },
    getAddresslist(e) {
      addresslist(e).then((res) => {
        if (res.data.length) {
          res.data = res.data.map((code) => {
            return {
              ...code,
              text: code.name,
              value: code.id,
            };
          });
        }
        this.deliveryList = res.data;
      });
    },
    // 选择商品
    inputChange(e) {
      this.establishFrom.newProduct = e;
    },
    // 选择付款类型
    changeType(e) {
      if (this.establishFrom.pay_type) {
        this.requiredTime = true;
      } else {
        this.requiredTime = false;
        this.establishFrom.repayment_time = "";
      }
    },

    submit() {
      this.$refs.form
        .validate()
        .then((res) => {
          this.establishFrom.product_info = this.establishFrom.newProduct.map(
            (code) => ({
              product_id: code.product_id,
              goods_id: code.goods_id,
              num: code.num,
            })
          );
          delete this.establishFrom.newProduct;

          addcreate(this.establishFrom).then((res) => {
            console.log(res, "4554545445");
            this.establishFrom = {};
            uni.navigateBack({
              delta: 1,
            });
          });
        })
        .catch((err) => {
          console.log("表单错误信息：", err);
        });
    },
  },
  computed: {
    // 仓库、客户、商品、客户地址、请先选择客户、请先选择仓库
    // 支付类型、付款时间、请选择付款时间、备注、请输入备注（0~50）
    Warehouse() {
      return this.$t("orderFrom.Warehouse");
    },
    Client() {
      return this.$t("orderFrom.Client");
    },
    Commodity() {
      return this.$t("orderFrom.Commodity");
    },
    ClientAddress() {
      return this.$t("orderFrom.Address");
    },
    Customer() {
      return this.$t("orderFrom.PleaseSelectTheCustomerFirst");
    },
    Selecthouse() {
      return this.$t("orderFrom.PleaseSelectAWarehouseFirst");
    },
    PaymentType() {
      return this.$t("orderFrom.PayType");
    },
    PaymentTime() {
      return this.$t("orderFrom.PayTime");
    },
	SelectTime() {
      return this.$t("orderFrom.PleaseSelectAPaymentTime");
    },
	Remark() {
      return this.$t("orderFrom.Remark");
    },
	EnterMark() {
      return this.$t("orderFrom.PleaseEnterAComment");
    },
	PleaseSelect(){
		return this.$t("common.PleaseSelect");
	}
  },
};
</script>

<style lang="scss" scoped>
.example {
  padding: 15px;
  background-color: #fff;
}

.commodity {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.commodity_box {
  overflow-y: auto;
  display: flex;
  flex-direction: column;
  gap: 20rpx;
  margin-bottom: 25rpx;
}

.operation {
  position: absolute;
  left: 0;
  right: 0;
  bottom: 10%;
  width: 500rpx;
}
</style>